package com.bcxj.routeplan.client;

import com.bcxj.internalcommon.constant.AmapConfigConstants;
import com.bcxj.internalcommon.entity.Weather;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * ClassName: WeatherClient
 * Package: com.bcxj.routeplan.client
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/4/25 14:06
 * @Version 1.0
 * @Since 1.0
 */
@Component
@Slf4j
public class WeatherClient {

    @Value("${weather-zhixin}")
    private String key;
    @Autowired
    private RestTemplate restTemplate;


    /**
     *
     * @param depLongitude
     * @param depLatitude
     * @return 返回null说明经纬度有问题
     */
    public Weather getWeather(String depLongitude, String depLatitude) {
        // 1.构建请求
        StringBuilder str = new StringBuilder();
        str.append(AmapConfigConstants.WATHER_ZHIXIN_HTTP);
        str.append("key=");
        str.append(key);
        str.append("&location=");
        str.append(depLatitude + ":" + depLongitude);
        str.append("&language=zh-Hans");
        str.append("&unit=c");
        log.info("getDirectionWalk url:{}", str);
        // 2. 发送请求
        ResponseEntity<String> entity = restTemplate.getForEntity(str.toString(), String.class);
        System.out.println(entity.getBody());
        String jsonStr = entity.getBody();


        // 获取天气
        // 将JSON字符串转换为JSONObject
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);

        if(!jsonObject.has("results")) {
            return null;
        }

        // 获取results数组的第一个元素
        JSONObject result =  jsonObject.getJSONArray("results").getJSONObject(0);

        // 获取now对象
        JSONObject now = result.getJSONObject("now");

        // 构建Weather对象
        return new Weather(
                now.getString("text"),
                Integer.parseInt(now.getString("temperature")) // 字符串转Integer
        );
    }
}
